package cn.dm.example.threadPool;

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
public class ThreadPoolExample4 {

    public static void main(String[] args) {

        // newScheduledThreadPool
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

        /**
         * 测试1 (与以前测例相同)
         */
//        for (int i = 0; i < 10; i++) {
//            final int index = i;
//            executorService.execute(new Runnable() {
//                @Override
//                public void run() {
//                    log.info("task:{}", index);
//                }
//            });
//        }

        /**
         * 测试2:延迟3s执行
         * (使用lambda表达式代替 new Runnable(){} 重写run()方法)
         */
//        executorService.schedule(() -> log.warn("schedule run"), 3, TimeUnit.SECONDS);

        // 前俩测试运行完程序需要关闭线程池,后俩测试因为定时执行故不能关闭线程池!
        // executorService.shutdown();


        /**
         * 测试3:定期执行,初始延迟1s然后每隔3s执行
         * (注:运行该测例时,要把最后一行代码 executorService.shutdown() 注释掉,否则线程池关闭了没法定时执行)
         *
         * 结果如下(由打印时间可知,每隔3s执行一次)
         * 21:37:57.098 [pool-1-thread-1] WARN cn.dm.example.threadPool.ThreadPoolExample4 - schedule run
         * 21:38:00.083 [pool-1-thread-1] WARN cn.dm.example.threadPool.ThreadPoolExample4 - schedule run
         * 21:38:03.081 [pool-1-thread-1] WARN cn.dm.example.threadPool.ThreadPoolExample4 - schedule run
         * ...
         */
//        executorService.scheduleAtFixedRate(() -> log.warn("schedule run"), 1, 3, TimeUnit.SECONDS);


        /**
         * 测试4:使用 Timer 类实现定时执行
         * schedule方法形参: schedule(TimerTask task, Date firstTime, long period)
         * (还有多个重载方法,自行查找学习)
         *
         * 结果(从当前时间开始,每隔5s执行一次)
         * 21:43:29.391 [Timer-0] WARN cn.dm.example.threadPool.ThreadPoolExample4 - timer run
         * 21:43:34.403 [Timer-0] WARN cn.dm.example.threadPool.ThreadPoolExample4 - timer run
         * 21:43:39.404 [Timer-0] WARN cn.dm.example.threadPool.ThreadPoolExample4 - timer run
         * ...
         */
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.warn("timer run");
            }
        }, new Date(), 5 * 1000);
    }
}
